/*
Copyright (C) 2009-2010 Xanadu Development Team

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General License
as published by the Free Software Foundation; version 2
of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General License for more details.

You should have received a copy of the GNU General License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#include "../server/Channel.h"
#include "Messenger.h"
#include "../tools/PacketCreator.h"
#include "../tools/Tools.h"

Messenger::Messenger(Player *player, int id) :
id(id),
members(new MessengerMembers)
{
	members->addMember(player);
}

Messenger::~Messenger() {
	delete members;
}

void Messengers::create(Player *player) {
	int id = Tools::random(1, 2147483647);
	Messenger *messenger = new Messenger(player, id);
	player->setMessenger(messenger);
	messengers[id] = messenger;
}

void Messengers::join(Player *player, int messengerId) {
	Messenger *messenger = getMessenger(messengerId);
	if (messenger == 0 || messenger->getMembersCount() == 3) {
		return;
	}
	player->setMessenger(messenger);
	bool pos1 = 0;
	bool pos2 = 0;
	hash_map <int, Player*>* ps = messenger->getMembers()->getPlayers();
	for(hash_map<int,Player*>::iterator iter = ps->begin(); iter != ps->end(); iter++) {
		player->send(PacketCreator().addMessengerPlayer(iter->second->getName(), iter->second, iter->second->getMessengerPosition(), iter->second->getChannel()->getID()));
		if (iter->second->getMessengerPosition() == 0) {
			pos1 = 1;
		}
		else if(iter->second->getMessengerPosition() == 1) {
			pos2 = 1;
		}
	}
	int position;
	if (pos1 == 0) {
		position = 0;
	} else if (pos2 == 0) {
		position = 1;
	} else {
		position = 2;
	}
	player->setMessengerPosition(position);
	messenger->getMembers()->addMember(player, position);
	messenger->getMembers()->send(PacketCreator().addMessengerPlayer(player->getName(), player, position, player->getChannel()->getID()));
	player->send(PacketCreator().joinMessenger(position));
}
